package com.sl.mes.app.controller.mm;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.sl.mes.app.dao.mm.AggMoVo;
import com.sl.mes.app.dao.mm.AggWeight;
import com.sl.mes.app.dao.mm.DoubleMmMo;
import com.sl.mes.app.service.mm.MoService;
import com.sl.mes.app.service.puboid.PubOidService;
import com.sl.mes.app.util.HttpUtil;
import com.sl.mes.app.util.JsonHandler;
import com.sl.mes.core.util.JacksonUtil;
import com.sl.mes.core.util.ResponseUtil;
import com.sl.mes.db.dao.BdWkMapper;
import com.sl.mes.db.dao.MmMoMapper;
import com.sl.mes.db.dao.MmPmoMapper;
import com.sl.mes.db.itf.bd.IBdMaterial;
import com.sl.mes.db.itf.bd.IBdWk;
import com.sl.mes.db.vo.*;
import net.sf.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mes/mmmo")
@Validated
public class MmMoController {
    @Resource
    private MoService moService;

    @Resource
    private PubOidService pubOidService;

    @Resource
    private IBdWk iBdWk;

    @Resource
    private MmMoMapper mmMoMapper;

    @Resource
    private BdWkMapper bdWkMapper;

    @Resource
    private IBdMaterial iBdMaterial;

    @Resource
    private MmPmoMapper mmPmoMapper;



    /**
     * 根据流程订单号查询生产订单
     *
     * @param body
     * @param request
     * @return
     */
    @GetMapping("getAggMoVoByVbillcode")
    public Object getAggMoVoByVbillcode(@RequestBody String body, HttpServletRequest request) {
        String vbillcode = JacksonUtil.parseString(body, "vbillcode");
        Map<Object, Object> result = new HashMap<Object, Object>();
        if (vbillcode.equals("")) {
            //输入的id值为空
            return ResponseUtil.fail(1, "您输入的流程订单号为空");
        } else {
            AggMoVo aggMoVo = moService.getAggMoVoByVbillcode(vbillcode);
            result.put("vbillcode", aggMoVo);
        }
        return ResponseUtil.ok(result);
    }


    /**
     * 根据id查询生产订单
     *
     * @param body
     * @param request
     * @return
     */
    @PostMapping("getAggMoVoById")
    public Object getAggMoVoById(@RequestBody String body, HttpServletRequest request) {
        String cpmohid = JacksonUtil.parseString(body, "cpmohid");
        Map<Object, Object> result = new HashMap<Object, Object>();
        if (cpmohid.equals("")) {
            //输入的id值为空
            return ResponseUtil.fail(1, "您输入的id为空");
        } else {
            AggMoVo aggMoVo = moService.getAggMoVoById(cpmohid);
            result.put("mo", aggMoVo);
        }
        return ResponseUtil.ok(result);
    }

    /**
     * 新增生产订单
     *
     * @param body
     * @param request
     * @return
     */
    @PostMapping("addAggMoVo")
    @Transactional
    public Object addAggMoVo(@RequestBody String body, HttpServletRequest request) {
        JsonNode movo = (JsonNode) JacksonUtil.toNode(body);
        //组装AggMoVo
        AggMoVo aggMoVo = new AggMoVo();
        //表头vo
        JsonNode moHead = (JsonNode) ((JsonNode) ((JsonNode) movo.get("data")).get("mo")).get("moHeadVo");
        MmPmo moHeadVo = JsonHandler.fromJson(moHead.toString(), MmPmo.class);
        String id = pubOidService.generate();
        moHeadVo.setCpmohid(id);
        moHeadVo.setDr("0");
        moHeadVo.setTs(LocalDateTime.now());
        aggMoVo.setMoHeadVo(moHeadVo);
        //表体vos
        ArrayNode moBody = (ArrayNode) ((JsonNode) ((JsonNode) movo.get("data")).get("mo")).get("moBodyVo");
        List<MmMo> lstMoBodyVo = new ArrayList<>();
        String[] ids = pubOidService.generate(moBody.size());
        for (int i = 0; i < moBody.size(); i++) {
            MmMo itemVo = JsonHandler.fromJson(moBody.get(i).toString(), MmMo.class);
            itemVo.setCmoid(ids[i]);
            itemVo.setCpmohid(id);
            //状态
            itemVo.setFbillstatus(1);
            itemVo.setDr("0");
            itemVo.setTs(LocalDateTime.now());
            //初投
            itemVo.setVfree1("1");
            itemVo.setVrowno("10");
            lstMoBodyVo.add(itemVo);
        }
        aggMoVo.setMoBodyVo(lstMoBodyVo);

        //判断炉台是否已经使用
        for (MmMo mmMo :lstMoBodyVo){
                //根据表头的炉台pk进行查询
             BdWk bdWk =  iBdWk.findById(mmMo.getCwkid());
             if (bdWk==null){
                 return ResponseUtil.fail(-3,"请选择炉号!");
             }
            //说明炉台没有被使用
             if (bdWk.getVdef1() != null && bdWk.getVdef2() != null){
                 return ResponseUtil.fail(-1,"炉台正在被使用!");
             }else {
                 //表头pk
                 bdWk.setVdef1(id);
                 //表体pk
                 bdWk.setVdef2(mmMo.getCmoid());
                 //修改数据
                 bdWkMapper.updateByPrimaryKey(bdWk);
             }
        }
        //调用service的insert方法
        int res = moService.addMmPmo(aggMoVo);
        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("aggMoVo", aggMoVo);

        try {
        //生产订单返回给ncc进行配料
        String url ="http://192.168.110.13:8080/nccloud/hr/login/HttpSyncDataAction.do";
        Map<String,Object> paramsMap = new HashMap<>();
        Map sysParamMap=new HashMap();
        //设置参数中的json对象
        sysParamMap.put("cookiets","1640068633741");
        sysParamMap.put("pagecs", "1640068633741");
        sysParamMap.put("appcode","");
        //转换为json对象
        JSONObject sysParamJsonObj=JSONObject.fromObject(sysParamMap);
        paramsMap.put("sysParamJson", sysParamJsonObj);
            System.out.println(sysParamJsonObj);
        //将对象转换成json字符串
        String s= JSON.toJSONString(aggMoVo);
        String busiParamJson="{\"busidata\":"+s+",\"busitype\":\"mo\",\"busioperator\":\"add\",\"key\":\"eyJwa19ncm91cCI6IjAwMDFBMDEwMDAwMDAwMDAxUFFPIiwiZGF0YXNvdXJjZSI6ImRlc2lnbiIs\\r\\nInVzZXJjb2RlIjoiTFlGIiwidXNlcmlkIjoiMTAwMUEwMTAwMDAwMDAwMDAwSEsifQ==\"}";
        System.out.println(busiParamJson);
        paramsMap.put("busiParamJson", busiParamJson);

        System.out.println(paramsMap);
        HttpUtil.exeApplyJsonObjectRequest(url,paramsMap);

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (res>0){
            return ResponseUtil.ok(result);
        }else{
            return ResponseUtil.fail();
        }
    }

    /**
     * 删除生产订单
     *
     * @param body
     * @param request
     */
    @PostMapping("deleteAggMoVoById")
    public Object deleteAggMoVoById(@RequestBody String body, HttpServletRequest request){
        String cpmohid = JacksonUtil.parseString(body, "cpmohid");
        Map<Object, Object> result = new HashMap<Object, Object>();
        //把删除的生产订单进行返回
        AggMoVo deleteMoVo = moService.getAggMoVoById(cpmohid);
        result.put("deleteMoVo",deleteMoVo);
        //进行mes服务删除操作
        moService.deleteMmPmo(cpmohid);
        return ResponseUtil.ok(result);
    }


    /**
     * 根据炉号撤回初投信息
     *  要料页面删除功能
     * @param
     * @param
     */
    @PostMapping("deleteAggMoVoByVwkcode")
    @Transactional
    public Object deleteAggMoVoByVwkcode(String vwkcode){
        Map<Object, Object> result = new HashMap<Object, Object>();
        BdWk bdWk = iBdWk.findByVwkcode(vwkcode);
        MmMo mmMo = mmMoMapper.selectByPrimaryKey(bdWk.getVdef2());
        if (mmMo.getVfree1().equals("1")){
            String cpmohid = bdWk.getVdef1();
            //把删除的生产订单进行返回
            AggMoVo deleteMoVo = moService.getAggMoVoById(cpmohid);
            result.put("deleteMoVo",deleteMoVo);
            //进行删除操作
            moService.deleteMmPmo(cpmohid);
            //把炉台中生产订单的pk删除
            bdWk.setVdef1(null);
            bdWk.setVdef2(null);
            bdWkMapper.updateByPrimaryKey(bdWk);

            //初装信息进行撤回把删除的生产订单给到ncc也需要删除
            try {
                //把要删除的初装生产订单进行删除
                String url ="http://192.168.110.13:8080/nccloud/hr/login/HttpSyncDataAction.do";
                Map<String,Object> paramsMap = new HashMap<>();
                Map sysParamMap=new HashMap();
                //设置参数中的json对象
                sysParamMap.put("cookiets","1640068633741");
                sysParamMap.put("pagecs", "1640068633741");
                sysParamMap.put("appcode","");
                //转换为json对象
                JSONObject sysParamJsonObj=JSONObject.fromObject(sysParamMap);
                paramsMap.put("sysParamJson", sysParamJsonObj);
                System.out.println(sysParamJsonObj);
                //将对象转换成json字符串
                String s= JSON.toJSONString(deleteMoVo);
                String busiParamJson="{\"busidata\":"+s+",\"busitype\":\"mo\",\"busioperator\":\"del\",\"key\":\"eyJwa19ncm91cCI6IjAwMDFBMDEwMDAwMDAwMDAxUFFPIiwiZGF0YXNvdXJjZSI6ImRlc2lnbiIs\\r\\nInVzZXJjb2RlIjoiTFlGIiwidXNlcmlkIjoiMTAwMUEwMTAwMDAwMDAwMDAwSEsifQ==\"}";
                System.out.println(busiParamJson);
                paramsMap.put("busiParamJson", busiParamJson);

                HttpUtil.exeApplyJsonObjectRequest(url,paramsMap);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            //删除复投只需要删除复投添加的订单行
            int reg = mmMoMapper.deleteByPrimaryKey(bdWk.getVdef2());
            //清空炉台表体pk
            bdWk.setVdef2(null);
            bdWkMapper.updateByPrimaryKey(bdWk);

//            //获取想要删除的复投订单行
//            //把删除复投的生产订单表体进行删除
//            try {
//                String url ="http://192.168.110.13:8080/nccloud/hr/login/HttpSyncDataAction.do";
//                Map<String,Object> paramsMap = new HashMap<>();
//                Map sysParamMap=new HashMap();
//                //设置参数中的json对象
//                sysParamMap.put("cookiets","1640068633741");
//                sysParamMap.put("pagecs", "1640068633741");
//                sysParamMap.put("appcode","");
//                //转换为json对象
//                JSONObject sysParamJsonObj=JSONObject.fromObject(sysParamMap);
//                paramsMap.put("sysParamJson", sysParamJsonObj);
//                System.out.println(sysParamJsonObj);
//                //将对象转换成json字符串
//                String s= JSON.toJSONString();
//                String busiParamJson="{\"busidata\":"+s+",\"busitype\":\"mo\",\"busioperator\":\"del\",\"key\":\"eyJwa19ncm91cCI6IjAwMDFBMDEwMDAwMDAwMDAxUFFPIiwiZGF0YXNvdXJjZSI6ImRlc2lnbiIs\\r\\nInVzZXJjb2RlIjoiTFlGIiwidXNlcmlkIjoiMTAwMUEwMTAwMDAwMDAwMDAwSEsifQ==\"}";
//                System.out.println(busiParamJson);
//                paramsMap.put("busiParamJson", busiParamJson);
//
//                HttpUtil.exeApplyJsonObjectRequest(url,paramsMap);
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }

            result.put(1,"删除复投成功");
        }
        return ResponseUtil.ok(result);
    }


    /**
     * 修改生产订单
     *
     * @param body
     * @param request
     */
    @PostMapping("updataAggMoVoById")
    public Object updataAggMoVoById(@RequestBody String body, HttpServletRequest request) {
        JsonNode movo = (JsonNode) JacksonUtil.toNode(body);
        //修改后单据AggMoVo
        //表头vo
        AggMoVo updatedAggMoVo = new AggMoVo();
        JsonNode moHead = (JsonNode) ((JsonNode) ((JsonNode) movo.get("data")).get("mo")).get("moHeadVo");
        MmPmo moHeadVo = JsonHandler.fromJson(moHead.toString(), MmPmo.class);
        updatedAggMoVo.setMoHeadVo(moHeadVo);

        //修改前单据
        String cpmohid = moHeadVo.getCpmohid() == null ? "" : moHeadVo.getCpmohid();
        AggMoVo orignAggVo = moService.getAggMoVoById(cpmohid);
        MmPmo orignMmPmo = orignAggVo.getMoHeadVo();
        List<MmMo> orignMoBody = orignAggVo.getMoBodyVo();

        //表体vos
        ArrayNode moBody = (ArrayNode) ((JsonNode) ((JsonNode) movo.get("data")).get("mo")).get("moBodyVo");
        String[] ids = pubOidService.generate(moBody.size());
        List<MmMo> lstNewBody = new ArrayList<MmMo>();
        List<MmMo> lstUpdateBody = new ArrayList<MmMo>();
        List<MmMo> lstfinalBody=new ArrayList<MmMo>();
        for (int i = 0; i < moBody.size(); i++) {
            MmMo itemVo = JsonHandler.fromJson(moBody.get(i).toString(), MmMo.class);
            String itemid = itemVo.getCmoid() == null ? "" : itemVo.getCmoid();
            itemVo.setCpmohid(cpmohid);
            if (itemid.equals("")) {
                String bodyid = pubOidService.generate();
                itemVo.setCmoid(bodyid);
                lstNewBody.add(itemVo);
            } else {
                lstUpdateBody.add(itemVo);
                orignMoBody.remove(itemVo);
            }
            lstfinalBody.add(itemVo);
        }
        updatedAggMoVo.setMoBodyVo(lstfinalBody);

        AggMoVo updateAggvo = new AggMoVo();
        AggMoVo newAggvo = new AggMoVo();
        AggMoVo delAggvo = new AggMoVo();
        if (lstNewBody.size() > 0) {
            newAggvo.setMoHeadVo(moHeadVo);
            newAggvo.setMoBodyVo(lstNewBody);
        } else {
            newAggvo = null;
        }
        if (lstUpdateBody.size() > 0) {
            updateAggvo.setMoHeadVo(moHeadVo);
            updateAggvo.setMoBodyVo(lstNewBody);
        } else {
            updateAggvo = null;
        }
        if (orignMoBody.size() > 0) {
            delAggvo.setMoHeadVo(orignMmPmo);
            delAggvo.setMoBodyVo(orignMoBody);
        }
        //调用service的insert方法
        boolean res = moService.updataMmPmo(updateAggvo, newAggvo, delAggvo);
        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("aggmovo", updatedAggMoVo);
        if (res){
            return ResponseUtil.ok(result);
        }else{
            return ResponseUtil.fail(-1,"添加失败");
        }

    }

    /**
     * 复投根据炉号进行查询
     * @return
     */
    @GetMapping("doubleMmMobyVwkcode")
    public Object doubleMmMobyVwkcode(String vwkcode){
        Map<Object,Object> result = new HashMap<>();
        DoubleMmMo doubleMmMo = new DoubleMmMo();

        BdWk bdWk = iBdWk.findByVwkcode(vwkcode);
        if (bdWk.getVdef1()==null && bdWk.getVdef2()==null){
            return ResponseUtil.fail(-1,"请先进行初投");
        }
        MmMo  mmMo = mmMoMapper.selectByPrimaryKey(bdWk.getVdef2());

        //判断是否可以复投
        if (mmMo.getFbillstatus()!=3 || mmMo.getFbillstatus()!=4){
            return ResponseUtil.fail(-9,"不允许进行复投");
        }
        //要料次数
        String num = mmMo.getVfree1();
        int a = Integer.parseInt(num);
        a++;
        //物料名称
       BdMaterial bdMaterial =iBdMaterial.findById(mmMo.getCmaterialid());
        String name =bdMaterial.getName();

        doubleMmMo.setVwkcode(vwkcode);
        doubleMmMo.setNum(a);
        doubleMmMo.setNamePk(mmMo.getCmaterialid());
        doubleMmMo.setName(name);
        doubleMmMo.setModel("300");
        doubleMmMo.setCrucible("400");
        doubleMmMo.setRemaining("150");

        result.put("doubleMmMo",doubleMmMo);

        return ResponseUtil.ok(result);
    }

    /**
     * 复投提交
     * @return
     */
    @PostMapping("insertDoubleMmMo")
    @Transactional
    public Object insertDoubleMmMo(@RequestBody String body, HttpServletRequest request){
        Map<Object,Object> result = new HashMap<>();
        JsonNode movo = (JsonNode) JacksonUtil.toNode(body);
        JsonNode moBody = (JsonNode) ((JsonNode) movo.get("data")).get("doubleMmMo");
        DoubleMmMo mmMo  = JsonHandler.fromJson(moBody.toString(), DoubleMmMo.class);
        //获取炉号
        String vwkcode = mmMo.getVwkcode();
        BdWk bdWk = iBdWk.findByVwkcode(vwkcode);

        //创建一个聚合vo
        AggMoVo aggMoVo = new AggMoVo();
        //获取表头信息
        MmPmo mmPmo = mmPmoMapper.selectByPrimaryKey(bdWk.getVdef1());
        aggMoVo.setMoHeadVo(mmPmo);
        List<MmMo> lstMmMo = new ArrayList<>();

        //判断是否先进行的初投
        if (bdWk.getVdef1()==null && bdWk.getVdef2()==null){
            return ResponseUtil.fail(-1,"请先进行初投!");
        }

        String cmoid =  bdWk.getVdef2();
        MmMo doubleMmMo = mmMoMapper.selectByPrimaryKey(cmoid);
        //判断之前是否完结
        if (doubleMmMo.getFbillstatus()!=4){
            return ResponseUtil.fail(-1,"请先完结之前操作");
        }
        //生成一个新的pk值
        String newCmoid = pubOidService.generate();
        doubleMmMo.setCmoid(newCmoid);

        //产品名称
        doubleMmMo.setCmaterialid(mmMo.getNamePk());
        //引晶型号
        doubleMmMo.setVdef12(mmMo.getModel());
        //取段锅位
        doubleMmMo.setVdef13(mmMo.getCrucible());
        //锅底余料量
        doubleMmMo.setVdef14(mmMo.getRemaining());
        //复投量
        doubleMmMo.setNplanputnum(mmMo.getNumber());
        //要料次数
        doubleMmMo.setVfree1(mmMo.getNum()+"");
        //要料次数
        String number = doubleMmMo.getVfree1();
        int a  =  Integer.parseInt(number);
        a++;
        doubleMmMo.setVfree1(a+"");
        //行号
        String vrowno =  doubleMmMo.getVrowno();
        int hang = Integer.parseInt(vrowno);
        String newVrown = (hang+10)+"";
        doubleMmMo.setVrowno(newVrown);
        //行状态
        doubleMmMo.setFbillstatus(1);

        //把原来炉台中初投表体的pk改变成复投的pk
        bdWk.setVdef2(newCmoid);
        //把炉台中表体的pk进行修改
        bdWkMapper.updateByPrimaryKey(bdWk);

        mmMoMapper.insert(doubleMmMo);
        lstMmMo.add(doubleMmMo);
        aggMoVo.setMoBodyVo(lstMmMo);
        result.put("doubleMmMo",doubleMmMo);

        //复投传到ncc
        String url ="http://192.168.110.13:8080/nccloud/hr/login/HttpSyncDataAction.do";
        Map<String,Object> paramsMap = new HashMap<>();
        Map sysParamMap=new HashMap();
        //设置参数中的json对象
        sysParamMap.put("cookiets","1640068633741");
        sysParamMap.put("pagecs", "1640068633741");
        sysParamMap.put("appcode","");
        //转换为json对象
        JSONObject sysParamJsonObj=JSONObject.fromObject(sysParamMap);
        paramsMap.put("sysParamJson", sysParamJsonObj);
        //将对象转换成json字符串
        String s= JSON.toJSONString(aggMoVo);
        System.out.println(s);
        String busiParamJson="{\"busidata\":"+s+",\"busitype\":\"mo\",\"busioperator\":\"update\",\"key\":\"eyJwa19ncm91cCI6IjAwMDFBMDEwMDAwMDAwMDAxUFFPIiwiZGF0YXNvdXJjZSI6ImRlc2lnbiIs\\\\r\\\\nInVzZXJjb2RlIjoiTFlGIiwidXNlcmlkIjoiMTAwMUEwMTAwMDAwMDAwMDAwSEsifQ==\"}";
        paramsMap.put("busiParamJson", busiParamJson);
        try {
            HttpUtil.exeApplyJsonObjectRequest(url,paramsMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseUtil.ok(result);

    }

    /**
     * 称重
     * 根据炉号查询物料名称
     */
    @GetMapping("addWeightByVwkcode")
    public Object  addWeightByVwkcode(String vwkcode){
        Map<Object,Object> result = new HashMap<>();
        //根据炉号获取当前炉台
        BdWk bdWk = iBdWk.findByVwkcode(vwkcode);
        MmMo mmMo = mmMoMapper.selectByPrimaryKey(bdWk.getVdef2());
        BdMaterial bdMaterial = iBdMaterial.findById(mmMo.getCmaterialid());
        result.put("vwkcode",vwkcode);
        result.put("bdMaterial",bdMaterial.getName());
        return ResponseUtil.ok(result);
    }


    /**
     * 称重
     * 根据返回信息修改数据
     */
    @PostMapping("updateWeightMmMo")
    public Object  updateWeightMmMo(@RequestBody String body, HttpServletRequest request){
        Map<Object,Object> result = new HashMap<>();
        JsonNode movo = (JsonNode) JacksonUtil.toNode(body);
        JsonNode moBody = (JsonNode) ((JsonNode) movo.get("data")).get("AggWeight");
        AggWeight aggWeight = JsonHandler.fromJson(moBody.toString(), AggWeight.class);
        //炉号
        String vwkcode  = aggWeight.getVwkcode();
        //物料名称
        String material = aggWeight.getMaterial();
        //重量
        String weight = aggWeight.getWeight();

        BdWk bdWk = iBdWk.findByVwkcode(vwkcode);
        MmPmo mmPmo =mmPmoMapper.selectByPrimaryKey(bdWk.getVdef1());
        mmPmo.setVnote(weight);
        mmPmoMapper.updateByPrimaryKey(mmPmo);
        result.put("mmPmo",mmPmo);
        return ResponseUtil.ok(result);
    }

}
